package com.ruixin.base.annotation;

import com.ruixin.base.exception.BaseException;
import com.ruixin.base.util.BeanUtil;
import com.sun.istack.internal.NotNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * 注解处理类
 */
public class AnnotationHandler {

    /**
     * 创建Annotation
     * @param clz
     * @param values
     * @param <T>
     * @return
     * @throws BaseException
     */
    public static <T extends Annotation> T createAnnotation(@NotNull Class<T> clz, @NotNull Map<String,Object> values) throws BaseException {
        Class<InvocationHandler> aClass = (Class<InvocationHandler>) BeanUtil.newClass("sun.reflect.annotation.AnnotationInvocationHandler");
        InvocationHandler invocationHandler = BeanUtil.newInstance(aClass, clz, values);
        return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, invocationHandler);
    }

    /**
     * 获取父类注解
     * @param annotation
     * @param superClass
     * @param <T>
     * @return
     * @throws BaseException
     */
    public static <T extends Annotation> T getSuperAnnotation(@NotNull Annotation annotation,@NotNull Class<T> superClass) throws BaseException {
        Map<String, Object> values = BeanUtil.getAnnotationValues(annotation);
        return createAnnotation(superClass,values);
    }
}
